// 生成一个随机索引
export function getRandomColor(colorArr) {
  const randomIndex = Math.floor(Math.random() * colorArr.length)
  return colorArr[randomIndex]
}

// 获取多边形的宽高
export function getPolygonDimensions(points) {
  let minX = points[0].x
  let maxX = points[0].x
  let minY = points[0].y
  let maxY = points[0].y
  // 找到多边形的最左、最右、最上和最下的顶点
  for (let i = 1; i < points.length; i++) {
    minX = Math.min(minX, points[i].x)
    maxX = Math.max(maxX, points[i].x)
    minY = Math.min(minY, points[i].y)
    maxY = Math.max(maxY, points[i].y)
  }
  // 计算多边形的宽度和高度
  const width = maxX - minX
  const height = maxY - minY
  return { width, height, minX, minY }
}

// 缩放
export function resizeCallback(imgWidth, imgHeight) {
  let useColumnLayout = sessionStorage.getItem('useColumnLayout') === 'true'
  var w = document
    .querySelector('.diy-full-screen-container')
    .parentElement.getBoundingClientRect().width
  var h = document
    .querySelector('.diy-full-screen-container')
    .parentElement.getBoundingClientRect().height
  document.querySelector('.screen-container').style.flexDirection =
    w / h < imgWidth / imgHeight ? 'column' : ''
}

// 判断点是否在多边形内
export function isPointInPolygon(point, polygonPoints) {
  let inside = false
  for (
    let i = 0, j = polygonPoints.length - 1;
    i < polygonPoints.length;
    j = i++
  ) {
    const xi = polygonPoints[i].x
    const yi = polygonPoints[i].y
    const xj = polygonPoints[j].x
    const yj = polygonPoints[j].y

    const intersect =
      yi > point.y !== yj > point.y &&
      point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi
    if (intersect) inside = !inside
  }

  return inside
}
